package com.flyou.ccnucenter.ui.frgment.Departments;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.flyou.ccnucenter.Constant;
import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.adapter.DepartmentAdapter;
import com.flyou.ccnucenter.domain.News;
import com.flyou.ccnucenter.ui.activity.NewsDetialActivity;
import com.flyou.ccnucenter.ui.frgment.BaseFragment;
import com.flyou.ccnucenter.utils.MyLog;
import com.flyou.ccnucenter.utils.SPUtils;
import com.flyou.ccnucenter.utils.UrlUtils.NewsUrl;
import com.flyou.ccnucenter.utils.UrlUtils.departments.ComputerUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.FaUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.HuaXueUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.HuanJingUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.JYXXUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.JkyUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.LiShiUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.MinShengUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.ShangUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.WenXueUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.XinWenUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.YaoUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.YiUrlPaster;
import com.flyou.ccnucenter.utils.UrlUtils.departments.ZheXueUrlPaster;
import com.flyou.ccnucenter.widget.XListView.XListView;
import com.flyou.ccnucenter.widget.loading.LoadingView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.Subscriber;

import java.util.List;


public class JYXXFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private Button reTry;
    private RelativeLayout mFailed_view;
    private LoadingView mLoadingView;
    private String mClassName="JiaoKeYuanFragment";
    private DepartmentAdapter mAdapter;
    private int mTempCount = 1;
    private int count = 1;
    private View mPaentView;
    private SwipeRefreshLayout mSwipeLayout;
    private XListView mXListView;


    @Override
    protected View onCreatView(LayoutInflater inflater, ViewGroup container) {
        mPaentView = inflater.inflate(R.layout.fragment_jiao_ke_yuan, container, false);

        return mPaentView;
    }

    @Override
    protected void initData() {
        mClassName = getClass().getSimpleName();
//       获取数据（判断是从本地还是从网络获取）
        GetData();


    }

    private void GetData() {
        if (TextUtils.isEmpty((String) SPUtils.get(context, mClassName, ""))) {
//            从网络获取
            MyLog.i(mClassName, " 从网络获取");
            MyLog.i(mClassName, NewsUrl.GetUrlByClassName(mClassName, count));
            new getDate().execute(NewsUrl.GetUrlByClassName(mClassName, count));
        } else {
//            从本地获取
            MyLog.i(mClassName, "从本地获取");
            String jsonData = (String) SPUtils.get(context, mClassName, "");
            Gson gson = new Gson();
            List<News> newData = gson.fromJson(jsonData, new TypeToken<List<News>>() {
            }.getType());
            if (mAdapter == null) {
                mLoadingView.setVisibility(View.GONE);
                mAdapter = new DepartmentAdapter(context, newData);
                mXListView.setAdapter(mAdapter);
                mXListView.setOnItemClickListener(DepartmentItemClickLicener);
            }
            else {
                mLoadingView.setVisibility(View.GONE);
                mXListView.setAdapter(mAdapter);
                mXListView.setOnItemClickListener(DepartmentItemClickLicener);
            }
        }
    }

    @Override
    protected void initView() {
        reTry = (Button) mPaentView.findViewById(R.id.reTry);
        reTry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                重新加载数据
                new getDate().execute(NewsUrl.GetUrlByClassName(mClassName, 1));
                mFailed_view.setVisibility(View.GONE);
                mLoadingView.setVisibility(View.VISIBLE);
            }
        });
//        连接错误页面
        mFailed_view = (RelativeLayout) mPaentView.findViewById(R.id.failed_view);

        mLoadingView = (LoadingView) mPaentView.findViewById(R.id.loadingView);
        mLoadingView.setLoadingText("正在拼命加载数据……");

        mLoadingView.setVisibility(View.VISIBLE);
        mXListView = (XListView) mPaentView.findViewById(R.id.listView);
        mXListView.setPullRefreshEnable(false);
        mXListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {

            }

            @Override
            public void onLoadMore() {
                count++;
                new getDate().execute(NewsUrl.GetUrlByClassName(mClassName, count));
                mTempCount = count;
            }
        });
        mXListView.setPullLoadEnable(true);
        mSwipeLayout = (SwipeRefreshLayout) mPaentView.findViewById(R.id.swipe_container);
        mSwipeLayout.setOnRefreshListener(this);
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);

    }

    @Override
    public void onRefresh() {
        mTempCount = 1;
        new getDate().execute(NewsUrl.GetUrlByClassName(mClassName, 1));

    }


    class getDate extends AsyncTask<String, List<News>, List<News>> {
        @Override
        protected List<News> doInBackground(String... params) {
            List<News> newses=null;
            switch (mClassName) {

                case "JiaoKeYuanFragment":
                    newses=JkyUrlPaster.GetShow(params[0]);
                    break;
                case "MinShengFragment":
                    newses= MinShengUrlPaster.GetShow(params[0]);
                    break;
                case "HuaXueFragment":
                    newses= HuaXueUrlPaster.GetShow(params[0]);
                    break;
                case "WenXueFragment":
                    newses= WenXueUrlPaster.GetShow(params[0]);
                    break;
                case "YaoXueFragment":
                    newses= YaoUrlPaster.GetShow(params[0]);
                    break;

                case "YiXueFragment":
                    newses= YiUrlPaster.GetShow(params[0]);
                    break;
                case "HuanJingFragment":
                    newses= HuanJingUrlPaster.GetShow(params[0]);
                    break;
                case "JiSuanJiFragment":
                    newses= ComputerUrlPaster.GetShow(params[0]);
                    break;
                case "ShengMingFragment":
                    newses=MinShengUrlPaster.GetShow(params[0]);
                    break;
                case "ZheXueFragment":
                    newses= ZheXueUrlPaster.GetShow(params[0]);
                    break;
                case "ShangFragment":
                    newses= ShangUrlPaster.GetShow(params[0]);
                    break;
                case "LiShiFragment":
                    newses= LiShiUrlPaster.GetShow(params[0]);
                    break;
                case "XinWenFragment":
                    newses = XinWenUrlPaster.GetShow(params[0]);
                    break;  case "FaFragment":
                    newses = FaUrlPaster.GetShow(params[0]);
                    break; case "JYXXFragment":
                    newses = JYXXUrlPaster.GetShow(params[0]);
                    break;
            }

            return newses;
        }

        @Override
        protected void onPostExecute(List<News> newses) {
            if (newses == null) {

                mLoadingView.setVisibility(View.GONE);
                if (mAdapter == null) {
                    mFailed_view.setVisibility(View.VISIBLE);

                }
                Toast.makeText(context, "获取服务器数据失败，请稍后再试", Toast.LENGTH_SHORT).show();
                return;
            }
            if (mAdapter == null) {
                Gson gson = new Gson();
                String jsonData = gson.toJson(newses);
                SPUtils.put(context, mClassName, jsonData);

                mLoadingView.setVisibility(View.GONE);
                mAdapter = new DepartmentAdapter(context, newses);
                mXListView.setAdapter(mAdapter);
                mXListView.setOnItemClickListener(DepartmentItemClickLicener);
            } else {
                mSwipeLayout.setRefreshing(false);
                mXListView.stopLoadMore();
                if (mTempCount == 1) {

                    mAdapter.replaceAll(newses);
                    //只有刷新时才缓存到本地
                    Gson gson = new Gson();
                    String jsonData = gson.toJson(newses);
                    SPUtils.put(context, mClassName, jsonData);

                } else {
                    mAdapter.addAll(newses);
                }
            }

        }
    }

    AdapterView.OnItemClickListener DepartmentItemClickLicener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(context, NewsDetialActivity.class);
            Object item = mAdapter.getItem(position - 1);
            News news = (News) item;
            intent.putExtra(Constant.SCHOOL_NEWS_TITLE, news.getTitle());
            intent.putExtra(Constant.SCHOOL_NEWS_URL, news.getUrl());
            intent.putExtra(Constant.DEPARTMENT_NAME, mClassName);
            context.startActivity(intent);
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(mClassName);
        Log.d("HuaXueFragment", "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d("HuaXueFragment", "onPause");
        MobclickAgent.onPageEnd(mClassName);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.d("HuaXueFragment", "onCreate");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroy() {
        Log.d("HuaXueFragment", "onDestroy");
        super.onDestroy();
    }

    @Subscriber(tag = "onDepartmentDestroy")
    public void destory(String tag) {


    }
}
